package com.ruoyi.system.api.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.mapper.*;
import com.ruoyi.system.api.service.CcService;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.service.IReportInfoService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.util.ObjectUtils;

/**
 * 服务通知的子服务与报告关联Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-03
 */
@Service
public class ReportInfoServiceImpl implements IReportInfoService {

    @Autowired
    private ReportInfoMapper stReportInfoMapper;

    @Autowired
    private StReportPortMapper stReportPortMapperst;

    /**
     * 调用CC接口service
     */
    @Autowired
    private CcService ccService;

    @Autowired
    private ServiceNoticeMapper serviceNoticeMapper;

    @Autowired
    private ServiceLogMapper serviceLogMapper;
    /**
     * 报告与备件的关系表
     */
    @Autowired
    private StReportPortMapper reportPortMapper;

    @Autowired
    private PlanDetailsMapper planDetailsMapper;

    @Autowired
    private ServiceDetailsMapper serviceDetailsMapper;


    /**
     * 查询服务通知的子服务与报告关联
     *
     * @param id 服务通知的子服务与报告关联ID
     * @return 服务通知的子服务与报告关联
     */
    @Override
    public ReportInfo selectStReportInfoById(Long id) {
        return stReportInfoMapper.selectStReportInfoById(id);
    }

    /**
     * 查询服务通知的子服务与报告关联列表
     *
     * @param stReportInfo 服务通知的子服务与报告关联
     * @return 服务通知的子服务与报告关联
     */
    @Override
    public List<ReportInfo> selectStReportInfoList(ReportInfo stReportInfo) {
        return stReportInfoMapper.selectStReportInfoList(stReportInfo);
    }

    /**
     * 新增服务通知的子服务与报告关联
     *
     * @param stReportInfo 服务通知的子服务与报告关联
     * @return 结果
     */
    @Override
    public int insertStReportInfo(ReportInfo stReportInfo) {
        stReportInfo.setCreateTime(DateUtils.getNowDate());
        return stReportInfoMapper.insertStReportInfo(stReportInfo);
    }

    /**
     * 修改服务通知的子服务与报告关联
     *
     * @param stReportInfo 服务通知的子服务与报告关联
     * @return 结果
     */
    @Override
    public int updateStReportInfo(ReportInfo stReportInfo) {
        stReportInfo.setUpdateTime(DateUtils.getNowDate());
        return stReportInfoMapper.updateStReportInfo(stReportInfo);
    }

    /**
     * 删除服务通知的子服务与报告关联对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStReportInfoByIds(String ids) {
        return stReportInfoMapper.deleteStReportInfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除服务通知的子服务与报告关联信息
     *
     * @param id 服务通知的子服务与报告关联ID
     * @return 结果
     */
    @Override
    public int deleteStReportInfoById(Long id) {
        return stReportInfoMapper.deleteStReportInfoById(id);
    }

    public void deleteServicetReportPort(Long id) {
        List<StReportPort> currentTypePortDatas = reportPortMapper.selectServicetReportPortByReportIdAndPortType(id);
        for (StReportPort stReportPort : currentTypePortDatas) {
            if (!ObjectUtils.isEmpty(stReportPort)) {
                ccService.addCCParts(stReportPort.getPid());
            }
        }
    }

    public void deleteErrorReportPort(Long id) {
        List<StReportPort> currentTypePortDatas = reportPortMapper.selectErrorReportPortByReportIdAndPortType(id);
        for (StReportPort stReportPort : currentTypePortDatas) {
            if (!ObjectUtils.isEmpty(stReportPort)) {
                ccService.addCCParts(stReportPort.getPid());
            }
        }
    }

    public void deleteHotReportPort(Long id) {
        List<StReportPort> currentTypePortDatas = reportPortMapper.selectHotReportPortByReportIdAndPortType(id);
        for (StReportPort stReportPort : currentTypePortDatas) {
            if (!ObjectUtils.isEmpty(stReportPort)) {
                ccService.addCCParts(stReportPort.getPid());
            }
        }
    }

    public void deleteAcceptReportPort(Long id) {
//        List<StReportPort> currentTypePortDatas = reportPortMapper.selectAcceptReportPortByReportIdAndPortType(id);
//        for (StReportPort stReportPort : currentTypePortDatas) {
//            if (!ObjectUtils.isEmpty(stReportPort)) {
//                ccService.addCCParts(stReportPort.getPid());
//            }
//        }
    }

    public void deleteInstallationReportPort(Long id) {
//        List<StReportPort> currentTypePortDatas = reportPortMapper.selectInstallationReportPortByReportIdAndPortType(id);
//        for (StReportPort stReportPort : currentTypePortDatas) {
//            if (!ObjectUtils.isEmpty(stReportPort)) {
//                ccService.addCCParts(stReportPort.getPid());
//            }
//        }
    }

    public void deletePhoneReportPort(Long id) {
        List<StReportPort> currentTypePortDatas = reportPortMapper.selectPhoneReportPortByReportIdAndPortType(id);
       // List<StReportPort> currentTypePortDatas = reportPortMapper.selectServicetReportPortByReportIdAndPortType(id);

        for (StReportPort stReportPort : currentTypePortDatas) {
            if (!ObjectUtils.isEmpty(stReportPort)) {
                ccService.addCCParts(stReportPort.getPid());
            }
        }
    }

    /**
     * 删除报告
     *
     * @param id
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/6 9:53 上午
     */
    @Override
    public ResponseWithData<?> deleteReport(Long id, Long enginnerId, String serviceNo, String helpId, String type) throws Exception {
        if (null == id) {
            return new ResponseWithData<>().error().msg("id cannot be empty");
        }
        // 查询服务报告信息数据
        ReportInfo reportInfo = stReportInfoMapper.selectStReportInfoById(id);
        if (null == reportInfo) {
            return new ResponseWithData<>().error().msg("报告不存在");
        }

        if (!(enginnerId+"").equals(reportInfo.getEnginnerId()+"")) {
            String name=reportInfo.getFseName();
            return new ResponseWithData<>().error().msg("你不能删除"+name+"的报告, 如需删除请联系"+name);
        }

        //更新CC备件状态为未使用--服务报告
        if (StringUtils.equals("1", type)) {
            deleteServicetReportPort(id);

        }
        if (StringUtils.equals("2", type)) {
            deleteErrorReportPort(id);
        }
        if (StringUtils.equals("3", type)) {
            deleteHotReportPort(id);
        }
        if (StringUtils.equals("4", type)) {
            deleteAcceptReportPort(id);
        }
        if (StringUtils.equals("5", type)) {
            deleteInstallationReportPort(id);
        }
        if (StringUtils.equals("6", type)) {
            deletePhoneReportPort(id);
        }
        JSONObject obj = new JSONObject();
        String state = "0";
        obj.put("state", state);
        // 未提交到CC删除本地数据
        if ("0".equals(reportInfo.getSyncFlag())) {
                if (1 == reportInfo.getRelServiceNo()) {
                    // 现场服务报告 解除日志关联
                    ServiceLog serviceLog = new ServiceLog();
                    serviceLog.setReportId(reportInfo.getId().toString());
                    List<ServiceLog> serviceLogs = serviceLogMapper.selectServiceLogList(serviceLog);
                    if (StringUtils.isNotEmpty(serviceLogs)) {
                        for (ServiceLog serviceLogTmp : serviceLogs) {
                            serviceLogTmp.setUpdateBy(enginnerId + "");
                            serviceLogTmp.setUpdateTime(new Date());
                            serviceLogMapper.updateReoprtId(serviceLogTmp);
                        }
                    }
                }

                reportInfo.setUpdateBy(enginnerId + "");
                reportInfo.setUpdateTime(new Date());
                reportInfo.setDelFlag("2");
                reportInfo.setSyncFlag("0");
                stReportInfoMapper.updateStReportInfo(reportInfo);
                obj.put("state", state);


               //删除草稿备件信息
                StReportPort searchStReportPort = new StReportPort();
                searchStReportPort.setServiceNo(serviceNo);
                searchStReportPort.setPortType("5");
                List<StReportPort> stReportPortList = stReportPortMapperst.selectStReportPortList(searchStReportPort);
                if(stReportPortList.size()>0){
                    for(StReportPort stReportPort:stReportPortList){
                        stReportPortMapperst.deleteStReportPortById(stReportPort.getId());
                    }
                }

            //ddCCParts

                return new ResponseWithData<>().success(obj).code(200).msg("删除服务报告成功");
        }
        // 提交到CC删除本地数据及CC数据
        else {

            List<ReportInfo> reportInfoList=stReportInfoMapper.getServiceReportInfo(serviceNo);

            String deletetFlag="0";
            if("2".equals(reportInfo.getServiceResult())){
                for (ReportInfo reportInfo1:reportInfoList){
                    if (StringUtils.equals("0",reportInfo1.getSyncFlag())){
                        continue;
                    }
                    if("1".equals(reportInfo1.getServiceResult())){
                        deletetFlag="1";
                        break;
                    }
                }
                if("1".equals(deletetFlag)){
                    return new ResponseWithData<>().code(203).msg("您已存在已完成报告，请先删除已完成报告!");
                }
            }

            // 请求CC接口 删除服务报告
            String response = ccService.deleteServiceReport(reportInfo.getEnginnerId(), reportInfo.getServiceNo(), id.toString());

            /** 如果调用接口异常直接返回 */
            if (null == response) {
                return new ResponseWithData().error().msg("删除服务报告失败 调用CC端删除服务报告接口发生异常").code(202);
            }

            JSONObject jsonObject = JSONObject.parseObject(response);
            String status = jsonObject.getString("status");
            if ("1".equals(status)) {
                // 删除成功，

                if (1 == reportInfo.getRelServiceNo()) {
                    // 现场服务报告 解除日志关联
                    ServiceLog serviceLog = new ServiceLog();
                    serviceLog.setReportId(reportInfo.getId().toString());
                    List<ServiceLog> serviceLogs = serviceLogMapper.selectServiceLogList(serviceLog);
                    if (StringUtils.isNotEmpty(serviceLogs)) {
                        for (ServiceLog serviceLogTmp : serviceLogs) {
                            serviceLogTmp.setUpdateBy(enginnerId + "");
                            serviceLogTmp.setUpdateTime(new Date());
                            serviceLogMapper.updateReoprtId(serviceLogTmp);
                        }
                    }
                    // 更新 报告状态 为已签离
                    ServiceDetails serviceDetailsFrom = new ServiceDetails();
                    serviceDetailsFrom.setFseId(enginnerId + "");
                    serviceDetailsFrom.setServiceNoticeId(reportInfo.getNoticeId());
                    List<ServiceDetails> serviceDetailItem = serviceDetailsMapper.selectServiceDetailsList(serviceDetailsFrom);
                    if (!StringUtils.equals("2", serviceDetailItem.get(0).getState().toString())) {
                        if (StringUtils.equals("1", reportInfo.getServiceResult())) {

                            PlanDetails planDetailsSearch= new PlanDetails();
                            planDetailsSearch.setFseId(enginnerId+"");
                            planDetailsSearch.setServiceNo(serviceNo);
                            planDetailsSearch.setState("1");
                            List<PlanDetails> planDetailsList=  planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);
                            if(planDetailsList.size()>0){
                                ServiceDetails serviceDetails = new ServiceDetails();
                                serviceDetails.setFseId(enginnerId + "");
                                serviceDetails.setState(3L);
                                serviceDetails.setUpdateTime(new Date());
                                serviceDetails.setServiceNoticeId(reportInfo.getNoticeId());
                                serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
                            }


                        }
                    }
                }

                if (6 == reportInfo.getRelServiceNo() && "1".equals(reportInfo.getServiceResult())) {
                    // 如果是已提交的已完成的电话解决报告删除,需要把已完成的状态变为已签离
                    ServiceDetails serviceDetailsFrom = new ServiceDetails();
                    serviceDetailsFrom.setFseId(enginnerId + "");
                    serviceDetailsFrom.setServiceNoticeId(reportInfo.getNoticeId());
                    List<ServiceDetails> serviceDetailItem = serviceDetailsMapper.selectServiceDetailsList(serviceDetailsFrom);
                    if (!StringUtils.equals("2", serviceDetailItem.get(0).getState().toString())) {
                        if (StringUtils.equals("1", reportInfo.getServiceResult())) {

                            // 没有去过现场的，删除已完成的电话解决报告， 状态变为1.
                            PlanDetails planDetailsNoLog= new PlanDetails();
                            planDetailsNoLog.setFseId(enginnerId+"");
                            planDetailsNoLog.setServiceNo(serviceNo);
                            planDetailsNoLog.setSignIn("1");
                            List<PlanDetails> planDetailsListLog=  planDetailsMapper.selectStPlanDetailsList(planDetailsNoLog);
                            //没去过现场
                            if(planDetailsListLog.size()==0){
                                ServiceDetails serviceDetailsCur =serviceDetailItem.get(0);
                                serviceDetailsCur.setState(1l);
                                serviceDetailsMapper.updateMyServiceDetails(serviceDetailsCur);
                            }else{
                                //曾经去过现场。
                                PlanDetails planDetailsSearch= new PlanDetails();
                                planDetailsSearch.setFseId(enginnerId+"");
                                planDetailsSearch.setServiceNo(serviceNo);
                                planDetailsSearch.setState("1");
                                List<PlanDetails> planDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailsSearch);
                                // 没有下次上门计划，状态不变。     状态为1，且有上门时间
                                if(planDetailsList.size()>0 && planDetailsList.get(0).getEstimatedVisitingTime()!=null) {
                                    ServiceDetails serviceDetails = new ServiceDetails();
                                    serviceDetails.setFseId(enginnerId + "");
                                    serviceDetails.setState(3L);
                                    serviceDetails.setUpdateTime(new Date());
                                    serviceDetails.setServiceNoticeId(reportInfo.getNoticeId());
                                    serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
                                }
                            }
                        }
                    }
//                    PlanDetails planDetails = new PlanDetails();
//                    planDetails.setUpdateBy(enginnerId + "");
//                    planDetails.setUpdateTime(new Date());
//                    planDetails.setState("3");
//                    planDetails.setId(reportInfo.getPlanId());
//                    planDetailsMapper.updateStPlanDetails(planDetails);
                    state = "1";
                    obj.put("state", state);
                }

                // 本地数据修改成删除状态
                reportInfo.setUpdateBy(enginnerId + "");
                reportInfo.setUpdateTime(new Date());
                reportInfo.setDelFlag("2");
                stReportInfoMapper.updateStReportInfo(reportInfo);

               //删除备件信息
                StReportPort searchStReportPort = new StReportPort();
                searchStReportPort.setServiceNo(serviceNo);
                searchStReportPort.setPortType("5");
                List<StReportPort> stReportPortList = stReportPortMapperst.selectStReportPortList(searchStReportPort);
                for(StReportPort stReportPort:stReportPortList){
                    stReportPortMapperst.deleteStReportPortById(stReportPort.getId());
                }

                return new ResponseWithData<>().success(obj).code(200).msg("删除服务报告成功");
            } else if ("2".equals(status)) {
                String message = jsonObject.getString("message");
                return new ResponseWithData().error().msg(message).code(201);
            } else {
                return new ResponseWithData().error().msg("删除服务报告失败 调用CC端删除服务报告接口发生异常").code(201);
            }
        }
    }

    @Override
    public List<ReportInfo> getReportList(ReportInfo stReportInfo) {
        return stReportInfoMapper.getReportList(stReportInfo);
    }


    @Override
    public List<ServiceNotice> getReportListByEnginnerId(ServiceNotice serviceNotice) {
        return serviceNoticeMapper.getListByEnginnerId(serviceNotice);
    }

    @Override
    public List<ReportInfo> getCustomerSignList(ReportInfo stReportInfo) {
        return stReportInfoMapper.getCustomerSignList(stReportInfo);
    }

    @Override
    public Map<String, Object> selectReportStartEndTime(String serviceNo, Long enginnerId) {
        return stReportInfoMapper.selectReportStartEndTime(serviceNo, enginnerId);
    }

    @Override
    public ResponseWithData<?> checkPhoneResolutionReportCompleted(String serviceNo, Long enginnerId, String planId) {
        List<ReportInfo> list = stReportInfoMapper.checkPhoneResolutionReportCompleted(serviceNo, enginnerId, planId);
        return new ResponseWithData<>().success(list).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> getServiceStatusByServiceNo(String serviceNo, String fseId) {
        List<Map> list = stReportInfoMapper.getServiceStatusByServiceNo(serviceNo, fseId);
        ReportInfo reportInfo = new ReportInfo();
        reportInfo.setServiceNo(serviceNo);
        reportInfo.setEnginnerId(new Long(fseId));
        reportInfo.setDelFlag("0");
        List<ReportInfo> reportInfoList = stReportInfoMapper.selectStReportInfoList(reportInfo);
        String isClosedReport = "0";
        for (ReportInfo reportInfo1 : reportInfoList) {
            if ("1".equals(reportInfo1.getServiceResult()) && "1".equals(reportInfo1.getSyncFlag())) {
                isClosedReport = "1";
                break;
            }
        }

        Map newkey = new HashMap();
        newkey.put("isClosedReport", isClosedReport);
        list.add(newkey);
        return new ResponseWithData<>().success(list).msg("查询成功").code(200);
    }

	@Override
	public List<ReportInfo> getAllCustomerSignList(ReportInfo stReportInfo) {
		// TODO Auto-generated method stub
		 return stReportInfoMapper.getAllCustomerSignList(stReportInfo);
	}

	@Override
	public ResponseWithData<?> getServiceSignPicHandle(String serviceNo) {
		return ccService.getServiceSignPicHandle(serviceNo);
	}
    public int updateStReportInfoByReportNo(ReportInfo stReportInfo){
        stReportInfo.setUpdateTime(DateUtils.getNowDate());
        return stReportInfoMapper.updateStReportInfoByReportNo(stReportInfo);
    }

}
